package com.huoyun.util;

import java.sql.SQLException;

import com.huoyun.util.bean.HYException;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 异常拦截器，将异常信息捕获，然后统一在异常信息页面进行显示处理
 * 
 * @author bishuxue
 * 
 */
public class ExceptionInterceptor extends AbstractInterceptor {
	private static final long serialVersionUID = -973363922210992103L;

	public static final String EXCEPTION = "commonErrorPage";
	
	public static final String ERRORMESSAGE = "errorMessage";

	@Override
	public String intercept(final ActionInvocation invocation) throws Exception {
		try {
			return invocation.invoke();
		} catch (final Exception e) {
			final ActionContext context = invocation.getInvocationContext();
			// final StringWriter writer = new StringWriter();
			// e.printStackTrace(new PrintWriter(writer, true));
			// context.put("tipMessage", e.getMessage());
			// context.put("tipCourse", writer.toString());

			if (e instanceof HYException) {
				final HYException hye = (HYException) e;
				context.put(ERRORMESSAGE, hye.getMessage());

			} 
			else if(e instanceof SQLException)
			{
				String tip = "数据库异常。";
				context.put(ERRORMESSAGE, tip);
			}
			else {
				context.put(ERRORMESSAGE, "未知异常");
			}
			return ConstantDefine.EXCEPTION_STEP;
		}

	}

	// private void ajaxIntercept(final ActionInvocation invocation) {
	// /**
	// * 读取文件，获取对应错误消息
	// */
	// final HttpServletResponse response = (HttpServletResponse) invocation
	// .getInvocationContext().get(StrutsStatics.HTTP_RESPONSE);
	// response.setCharacterEncoding("UTF-8");
	// /**
	// * 发送错误消息到页面
	// */
	// PrintWriter out;
	// try {
	// out = response.getWriter();
	// final Message msg = new Message(errorMsg);
	// // 把异常信息转换成json格式返回给前台
	// out.print(JSONObject.fromObject(msg).toString());
	// } catch (final IOException e1) {
	// throw e1;
	// }
	// }
}
